/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package portal.userManager;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Riso-Desktop
 */
@WebServlet(name = "Registracia", urlPatterns = {"/Registracia"})
public class Registracia extends HttpServlet {

    String driver = portal.constants.Database.DATABASE_DRIVER;
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    String userName = portal.constants.Database.DATABASE_USER;
    String password = portal.constants.Database.DATABASE_PASSWORD;
    String URL = portal.constants.Database.DATABASE_URL;
    PrintWriter out;
    //udaje o používatelovi
    String user = null;
    String heslo = null;
    String email = null;
    HttpSession session;

    @Override
    public void init() {
        try {
            super.init();
            Class.forName(driver);
            con = DriverManager.getConnection(URL, userName, password);
        } catch (Exception ex) {
        }
    }

    //kontrola či sa email už nachádza v databáze
    public int KontrolaUdajovVDB(String email, String meno) {
        int nachadzasa = -1;
        try {
            stmt = con.createStatement();
            rs = stmt.executeQuery("select * from user where email = '"+ email+"'");           
            if(!rs.next()){
                nachadzasa = 1;
            }else{
                //email je už obsadený
                nachadzasa = 2;
            }
            rs = stmt.executeQuery("select * from user where meno = '"+ meno+"'");
            if(!rs.next()){
            }else{
                //meno je už obsadené
                nachadzasa = 3;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nachadzasa;
    }
    
    private boolean ZaregistrujUsera(String Meno, String MD5hash_heslo,String email){
        boolean uspesne = false;
        try {
            stmt = con.createStatement();
            String sql = "insert into user (meno,heslo,email,datum_registracie) values('"+Meno+"','"+MD5hash_heslo+"', '"+email+"', '"+ new java.sql.Date(new java.util.Date().getTime())+"')";           
            
            stmt.executeUpdate(sql);
            rs = stmt.executeQuery("select max(id_usera) as iid,count(id_usera) as pocet from user where meno='"+
                    user+"' and heslo='"+new String(MD5hash_heslo) +"'");
            rs.next();
            int idusera = 0;
            if(rs.getInt("pocet")==1){
                idusera = rs.getInt("iid");
            }
            sql = "insert into user_nastavenia (id_usera) values("+idusera+")";
            stmt.executeUpdate(sql);
            uspesne = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uspesne;
    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        out = response.getWriter();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            user = request.getParameter("meno");
            heslo = request.getParameter("heslo");
            email = request.getParameter("email");
            byte[] nezakodovaneHeslo= heslo.getBytes("UTF-8");
            byte[] zakodovaneHeslo = md.digest(nezakodovaneHeslo);
            int vysledokKontroly = KontrolaUdajovVDB(email, user);
            if(vysledokKontroly == 1){
                ZaregistrujUsera(heslo, new String(zakodovaneHeslo), email);
                session = request.getSession();
                session.setAttribute("registracia", "uspesna");
                response.sendRedirect("login.jsp");
            }else if(vysledokKontroly == 2){ //email už je v databázy
                session = request.getSession();
                session.setAttribute("registracia", "email");
                response.sendRedirect("registracia.jsp");
            }else if(vysledokKontroly == 3){ //meno už je v databázy
                session = request.getSession();
                session.setAttribute("registracia", "meno");
                response.sendRedirect("registracia.jsp");
            }
            rs.close();
            stmt.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
